package com.utilities.parsers.gff3FileParser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

import com.utilities.parsers.gff3FileParser.ParseEvents.EventTypes;

public class ParseAllContigsFileParser   
{
	private LinkedList<ParseListener> eventListeners = new LinkedList<ParseListener>();
	
	public void addListener(ParseListener parseListener)
	{
		eventListeners.add(parseListener);
	}
	
	private void fireEvent(ParseEvents parseEvent)
	{
		for (ParseListener listener : eventListeners)
		{
			listener.handleEvent(parseEvent);
		}
	}
	
	public void parse(FileReader fileReader) throws IOException
	{
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		fireEvent(new ParseEvents(null,EventTypes.docStarted));
		String readLine = bufferedReader.readLine();
		while(readLine != null)
		{
			if (readLine.startsWith(">")) fireEvent(new ParseEvents(readLine,EventTypes.seqStarted));
			else if (readLine.startsWith("#")) fireEvent(new ParseEvents(readLine,EventTypes.headerRead));
			else if (readLine.contains("contig")) fireEvent(new ParseEvents(readLine, EventTypes.contigEncountered));
			else if (readLine.contains("gene")) fireEvent(new ParseEvents(readLine, EventTypes.geneEncountered));
			else if (readLine.contains("INVALIDATOR")) fireEvent(new ParseEvents(readLine, EventTypes.InvalidatorEncountered));
			else fireEvent(new ParseEvents(readLine,EventTypes.seqRead));
			readLine = bufferedReader.readLine();
		}
		fireEvent(new ParseEvents(null,EventTypes.docEnded));
	}
	
	public void removeAllListeners()
	{
		eventListeners.clear();
	}
	
	/**
	 * This method parses a non-commented line in a GFF3 file
	 * and returns the parameters in the form of a String array.
	 * param[0] = The ID of the landmark
	 * param[1] = source
	 * param[2] = type
	 * param[3] = start
	 * param[4] = end
	 * param[5] = score
	 * param[6] = strand
	 * param[7] = phase
	 * param[8] = attributes
	 * Attributes are delimited by ; and most of them are :
	 * Parent,ID,NAME,eVal,mM,gaps
	 * A type called INVALIDATOR may not have attributes (as of now).
	 * @param readLine
	 * @return
	 */
	public String[] parseGFF3FileLine(String readLine)
	{
		return readLine.split("\\t");
	}
}
